<template>
  <div class="ResumeTemplate tw-w-full">
    <div @click="add" class="add-btn template-item">
      <q-icon class="tw-w-full tw-h-full icon" size="50px" name="add"></q-icon>
    </div>
    <div v-for="item in templates" :key="item.dbId" class="template-item">
      <q-icon
        @click="openTemplate(item)"
        class="tw-w-full tw-h-full tw-cursor-pointer icon"
        size="50px"
        name="topic"
      ></q-icon>
      <q-btn size="sm" icon="more_horiz" class="tw-absolute template-more-icon" dense flat>
        <q-menu>
          <q-list dense padding class="tw-w-200px">
            <q-item @click="openTemplate(item)" clickable>
              <q-item-section>打开</q-item-section>
            </q-item>
            <q-item v-close-popup @click="renameTemplate(item)" clickable>
              <q-item-section>重命名</q-item-section>
            </q-item>
            <q-item v-close-popup @click="deleteTemplate(item)" clickable>
              <q-item-section>删除</q-item-section>
            </q-item>
          </q-list>
        </q-menu>
      </q-btn>
      <p class="tw-text-center label" style="font-size: 12px">
        <span>{{ item.label }}</span>
      </p>
    </div>
    <q-dialog v-model="rename">
      <q-card>
        <q-form @submit.prevent="confirmRename">
          <q-card-section>
            <q-input
              style="width: 200px"
              label="模板名称"
              v-model="currentTemplate.label"
            ></q-input>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn label="取消" flat @click="cancelRename"></q-btn>
            <q-btn label="确定" flat color="primary" type="submit"></q-btn> </q-card-actions
        ></q-form>
      </q-card>
    </q-dialog>
  </div>
</template>
<script>
import { defineComponent, ref, toRaw } from 'vue';
import { useRouter } from 'vue-router';
import { useNodeTreeStore } from 'src/stores/nodeTree';
import { serializer } from 'src/common/utils';
import { useQuasar } from 'quasar';
const apiFns = {
  findTemplate(id) {
    return window.DB.resume.get(id);
  },
  getTemplateList() {
    return window.DB.resume.filter((item) => !item.delete).toArray();
  },
  updateTemplate(data) {
    return window.DB.resume.put(data, data.dbId);
  },
  deleteTemplate(id) {
    // return window.DB.resume.delete(id);
    return window.DB.resume.update(id, { delete: true, deleteTime: new Date().getTime() });
  },
};
export default defineComponent({
  name: 'ResumeTemplate',
  setup() {
    const $q = useQuasar();
    const router = useRouter();
    const nodeTreeStore = useNodeTreeStore();
    const templates = ref([]);
    const currentTemplate = ref({});
    const rename = ref(false);
    const deleteTemplate = (item) => {
      $q.dialog({
        title: '提示',
        message: '确定删除吗？',
        cancel: true,
      })
        .onOk(async () => {
          try {
            $q.loading.show({ spinnerColor: 'primary' });
            await apiFns.deleteTemplate(item.dbId);
            getTemplateList();
            $q.notify({
              message: '删除成功',
              color: 'positive',
              position: 'top',
            });
          } catch (error) {
            console.error('删除失败', error);
            $q.loading.hide();
            $q.notify({
              type: 'negative',
              message: '删除失败',
            });
          }
        })
        .onCancel(() => {
          // console.log('Cancel')
        })
        .onDismiss(() => {
          // console.log('I am triggered on both OK and Cancel')
        });
    };
    const getTemplateList = async () => {
      try {
        // console.log('获取模板列表');
        $q.loading.show({ spinnerColor: 'primary' });
        const list = await apiFns.getTemplateList();
        templates.value = list;
        $q.loading.hide();
      } catch (error) {
        console.log('获取模板列表失败', error);
        $q.notify({
          message: '获取模板列表失败',
          color: 'negative',
          position: 'top',
        });
      }
    };
    const openTemplate = (item) => {
      console.log('item', item);
      item.children = serializer.deserialize(item.children);
      // console.log('item', item);
      nodeTreeStore.setNodeTree(item);
      router.push({
        name: 'BiographicalNotes',
      });
    };
    const renameTemplate = async (item) => {
      try {
        const template = await apiFns.findTemplate(item.dbId);
        currentTemplate.value = template;
        rename.value = true;
      } catch (error) {
        console.error('查询失败', error);
        $q.notify({
          message: '查询失败',
          color: 'negative',
          position: 'top',
        });
      }
    };
    const cancelRename = () => {
      currentTemplate.value = null;
      rename.value = false;
    };
    const confirmRename = () => {
      $q.loading.show({ spinnerColor: 'primary' });
      apiFns
        .updateTemplate(toRaw(currentTemplate.value))
        .then(() => {
          cancelRename();
          getTemplateList();
          $q.loading.hide();
          $q.notify({
            message: '修改成功',
            color: 'positive',
            position: 'top',
          });
        })
        .catch(() => {
          $q.loading.hide();
          cancelRename();
          getTemplateList();
          $q.notify({
            message: '修改失败',
            color: 'negative',
            position: 'top',
          });
        });
    };
    const add = () => {
      nodeTreeStore.clear();
      router.push({
        name: 'BiographicalNotes',
      });
    };
    getTemplateList();
    return {
      add,
      templates,
      openTemplate,
      renameTemplate,
      currentTemplate,
      rename,
      confirmRename,
      cancelRename,
      deleteTemplate,
    };
  },
});
</script>
<style scoped lang="scss">
.ResumeTemplate {
  --gap: 20px;
  display: grid;
  width: 100%;
  height: auto;
  row-gap: var(--gap);
  column-gap: var(--gap);
  grid-template-columns: repeat(auto-fill, 100px);
  .template-item {
    border: 1px solid transparent;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 100px;
    .icon {
      color: #ccc;
    }
    border-radius: 4px;
    .label {
      position: absolute;
      bottom: 5px;
    }
    &:hover {
      border: 1px solid $primary;
      color: $primary;
      .icon {
        color: $primary;
      }
    }
    .template-more-icon {
      right: 5px;
      top: 5px;
      cursor: pointer;
    }
  }
}
</style>
